

#include "ClientSocket.h"
#include "SocketException.h"
#include <iostream>
#include <string>
#include <boost/regex.h>
#include <stdio.h>
#include <cstdlib>
#include <errno.h>
#include <boost/lexical_cast.hpp>
#include <unistd.h>

using namespace std;


#define NUM_PARAMETERS 4
#define HTTP_LENGTH 6
#define BEGIN_FILEPATH url.find("/",HTTP_LENGTH+1)

//------------------------------------------//

bool checkUrl(string url);

//------------------------------------------//

int main ( int argc, char** argv )
{

	  if (argc!=NUM_PARAMETERS) {
	  		cout<<"error: Usage: client <URL> <Proxy-hostname> <proxy port>.\n";
	  		exit(1);
	  	}

	  	string url = argv[1];

	  	if(!checkUrl(url)){
	  		cout<<"error: Usage: client <URL> <Proxy-hostname> <proxy port>.\n";
	  		exit(1);
	  	}

	  	string host = url.substr(HTTP_LENGTH,BEGIN_FILEPATH-HTTP_LENGTH);

	  	string filePath = url.substr(BEGIN_FILEPATH);

	  	string request = "GET "+filePath+ " HTTP/1.0\r\nHost: "+host+"\r\n\r\n";

	  	string pHostName = argv[2];

	  	int port = atoi(argv[3]);

	  	cout<<"HTTP request =\n"<<request<<"\nLEN = "<<request.length()<<"\n";


	try{

      ClientSocket client_socket ( pHostName, port );

      string reply;

      try
	{
	  client_socket << request;

	  client_socket >> reply;
	}
      catch ( SocketException& ) {
    	  perror("error: "<< e.description()<<"\n");
    	  exit(1);
      }

      cout <<reply;

      int size = reply.size();

      printf("\n Total received response bytes: %d\n",size);

      //how do i close the connection?

    }
  catch ( SocketException& e )
    {
	  perror("error: "<< e.description()<<"\n");
	  exit(1);
    }

  return 0;
}



bool checkUrl(string url){

	string http = url.substr(0,HTTP_LENGTH);

	if(http!="http//")

		return false;


	if((unsigned)BEGIN_FILEPATH == string::npos)

		return false;


	return true;
}

